(function() {
  var that;
  // 游戏对象
  function Game(map) {
    // 游戏对象属性中，有食物，蛇和地图对象
    this.map = map;
    this.food = new Food();
    this.snake = new Snake();
    that = this;
  }
  // 游戏开始函数
  Game.prototype.start = function() {
    // 渲染蛇和食物对象
    this.food.render(this.map);
    this.snake.render(this.map);
    autoStart();
    change();
  }
  
  // 蛇自动移动函数
  function autoStart(){
    // 游戏开始，蛇向右移动
    var timer = setInterval(function () {
      // 定时器中的this指向的是window对象，因此需要将Game对象中的this储存到that中，否则无法调用snake对象
      that.snake.move();
      that.snake.del(that.map);
      that.snake.render(that.map);
      // 判断是否超出地图，超出则游戏结束 
      // 获取地图的最大位置
      var X = that.map.offsetWidth / that.snake.width;
      var Y = that.map.offsetHeight / that.snake.height;
      // console.log(X,Y);
      // 获取蛇头的位置
      var snakeHeadX = that.snake.body[0].x;
      var snakeHeadY = that.snake.body[0].y;
      // 判断蛇是否吃到食物
      var foodX = that.food.x;
      var foodY = that.food.y;
      var snakeX = snakeHeadX * that.snake.width;
      var snakeY = snakeHeadY * that.snake.height;
      // 判断是否撞到自己的身体
      for (var i = 1; i < that.snake.body.length; i++) {
        if (snakeHeadX === that.snake.body[i].x && snakeHeadY === that.snake.body[i].y){
          clearInterval(timer);
          alert("游戏结束！");
        }
      }
      if (foodX === snakeX && foodY === snakeY) {
        // 吃到食物，食物消失
        that.food.delFood(that.map);
        // 再随机渲染一个食物
        that.food.render(that.map);
        // 吃完食物，蛇需要变长一节,记录最后一节蛇节，再将其添加到蛇身体里
        var lastSnake = that.snake.body[that.snake.body.length - 1];
        that.snake.body.push({
          x: lastSnake.x,
          y: lastSnake.y,
          color: lastSnake.color
        })
      }
      // 判断是否超出地图
      if (snakeHeadX < 0 || snakeHeadX >= X || snakeHeadY < 0 || snakeHeadY >= Y) {
        // 停止定时器，游戏结束
        clearInterval(timer);
        alert("游戏结束！");
      }
    }, 150)
  }
  // 改变蛇的方向函数
  function change() {
    // 绑定键盘的上下左右按键，改变蛇的方向属性
    // 蛇不可以走回头路，因为会撞到自己的身体
    document.onkeydown = function(e) {
      switch(e.keyCode) {
        case 37:
          if(that.snake.direction != "right"){
            that.snake.direction = "left";
          }
          break;
        case 38:
          if (that.snake.direction != "down") {
            that.snake.direction = "up";
          }
          break;
        case 39:
          if (that.snake.direction != "left") {
            that.snake.direction = "right";
          }
          break;
        case 40:
          if (that.snake.direction != "up") {
            that.snake.direction = "down";
          }
          break;
      }
    }
  }
  window.Game = Game;
})();
// test
var map = document.getElementById("map");
var game = new Game(map);
game.start();
